using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using CometServiceDemo.LocalComunication;

namespace CometServiceDemo.Comet
{
    [Service]
    [IntentFilter(new String[] { "CometService" })]
    public class CometService : Service
    {
        public override IBinder OnBind(Intent intent)
        {
            return new CommonServiceBinder<CometService>(this);
        }
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(this.GetType().ToString(), "Service started");
            base.OnStartCommand(intent, flags, startId);            
            StartStreaming();
            return StartCommandResult.NotSticky;
        }

        private CometRequest request;
        const string CometUri = @"http://172.28.168.78:8888/streaming";
        public void StartStreaming()
        {
            if (request == null)
            {
                request = new CometRequest(CometUri);
                request.OnReceiveData += new OnReceiveDataDelegate(request_OnReceiveData);
            }
            request.BeginRequest();
            //ProcessStart();
        }

        public void RestartStreaming()
        {
            StopStreaming();
            request.BeginRequest();
            //ProcessStart();
        }

        void request_OnReceiveData(string data)
        {
            var intent = new Intent(MessageType.Chat);
            intent.PutExtra(MessageType.Chat,data);
            SendBroadcast(intent);
        }
        public void StopStreaming()
        {            
            request.StopRequest();
            request = null;
            //ProcessStop();
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            request = null;
            Log.Debug(this.GetType().ToString(), "Service stopped");
        }        
    }
}